package org.kl.bf.web.basic;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.kl.bf.entity.basic.Organization;
import org.kl.bf.entity.basic.Post;
import org.kl.bf.entity.easyui.EasyuiUtils;
import org.kl.bf.service.basic.OrganizationService;
import org.kl.bf.service.basic.PostService;
import org.kl.bf.utils.BasicConstants;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

/**
 * 岗位管理
 * 
 * @Author ymc
 * @CreateTime 2014-3-13 下午9:34:36
 */
@Controller
@RequestMapping(value = "/basic/post")
public class PostController extends BasicController {
	@Autowired
	private PostService postService;
	@Autowired
	private OrganizationService organizationService;

	@RequiresPermissions("post:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/postList";
	}

	@RequiresPermissions("post:list")
	@RequestMapping(value = "dataGrid/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			@PathVariable("id") String id) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		searchParams.put("EQ_organization.id", id);
		Page<Post> posts = postService.getPostInfo(searchParams, pageNumber, pageSize, sortType, orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(posts.getContent(), (int) posts.getTotalElements());
	}

	@RequiresPermissions("post:list")
	@RequestMapping(value = "postList", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String postList(@RequestParam(value = "orgId", defaultValue = "-1") String orgId) {
		List<Post> postList = new ArrayList<Post>();
		Post p = new Post();
		p.setPostName("所有内容");
		p.setId(" ");
		postList.add(p);
		if (!orgId.equals("-1")) {
			postList.addAll(postService.findByOrganizationIdAndEnable(orgId));
		}
		String result = jsonMapper.toJson(postList);
		return result;
	}

	@RequiresPermissions("post:list")
	@RequestMapping(value = "showInfo/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String showInfo(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			@PathVariable("id") String id) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		searchParams.put("EQ_organization.id", id);
		searchParams.put("EQ_enable", "1");
		Page<Post> posts = postService.getPostInfo(searchParams, pageNumber, pageSize, sortType, orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(posts.getContent(), (int) posts.getTotalElements());
	}

	@RequiresPermissions("post:export")
	@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			HttpServletResponse response, @RequestParam(value = "orgId", defaultValue = "-1") String orgId) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		if (!orgId.equals("-1")) {
			searchParams.put("EQ_organization.id", orgId);
		}
		List<Post> posts = postService.getAllPostInfo(searchParams,sortType, orderType);
		super.export(Post.class, response, posts, "岗位信息");
		return null;
	}

	@RequiresPermissions("post:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("post") Post post, @RequestParam(value = "orgId", defaultValue = "-1") String orgId,
			RedirectAttributes redirectAttributes, HttpSession session, ServletRequest request) {
		List<Post> postList = new ArrayList<Post>();
		if (StringUtils.equals(post.getDescription(), "请在这里输入职位描述")) {
			post.setDescription(null);
		}
		if (StringUtils.isBlank(post.getId())) {
			Organization organization = organizationService.getOrganization(orgId);
			if (organization != null) {
				post.setOrganization(organization);
			} else {
				return ajaxMsg("编辑失败!岗位所属组织必须输入", false, null);
			}
			if ((StringUtils.isBlank(post.getPostNo())) || (StringUtils.isBlank(post.getPostName()))) {
				return ajaxMsg("编辑失败!岗位编号以及岗位名称必须输入", false, null);
			}
			if ((postService.findByPostNoAndOrganizationId(post.getPostNo(), post.getOrganization().getId()) == null)
					&& (postService.findByPostNameAndOrganizationId(post.getPostName(), post.getOrganization().getId()) == null)) {
				try {
					postService.savePost(post);
				} catch (Exception e) {
					e.printStackTrace();
					return ajaxMsg("编辑失败[" + e.getMessage() + "]", false, null);
				}
				return ajaxMsg("编辑成功", true, null);
			} else {
				return ajaxMsg("编辑失败!岗位编号或岗位名称在当前组织及公中已存在", false, null);
			}

		} else {
			if (post.getHigherPostId().equals(post.getId())) {
				return ajaxMsg("编辑失败!自身不能作为自身的上级岗位", false, null);
			}
			if (post.getEnable() != BasicConstants.YES_INT) {
				postList = postService.findByHigherPostId(post.getId());
			}
			Post newPostone = postService.findByPostNoAndOrganizationId(post.getPostNo(), post.getOrganization().getId());
			Post newPosttwo = postService.findByPostNameAndOrganizationId(post.getPostName(), post.getOrganization().getId());
			if (newPostone != null && !StringUtils.equals(newPostone.getId(), post.getId())) {
				return ajaxMsg("编辑失败!岗位编号在当前组织中已存在", false, null);
			}
			if (newPosttwo != null && !StringUtils.equals(newPosttwo.getId(), post.getId())) {
				return ajaxMsg("编辑失败!岗位名称在当前组织中已存在", false, null);
			}
			try {
				if (postList.size() != 0) {
					for (Post po : postList) {
						po.setHigherPostId("");
						postService.savePost(po);
					}
				}
				postService.savePost(post);
			} catch (Exception e) {
				e.printStackTrace();
				return ajaxMsg("编辑失败[" + e.getMessage() + "]", false, null);
			}
			return ajaxMsg("编辑成功", true, null);
		}
	}

	// 获取显示组织名称
	@RequiresPermissions("post:update")
	@RequestMapping(value = "orgList/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String orgList(@PathVariable("id") String id, RedirectAttributes redirectAttributes, HttpSession session) {
		List<Organization> organizations = organizationService.getAllOrganization();
		String result = jsonMapper.toJson(organizations);
		return result;
	}

	@RequiresPermissions({ "post:delete", "post:update" })
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes, HttpSession session) {
		postService.deletePost(id);
		return ajaxMsg("删除成功", true, null);
	}

	@RequiresPermissions({ "post:delete" })
	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = postService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getPost(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("post", postService.getPost(id));
		}
	}
}
